import matplotlib.pyplot as plt
import numpy as np
import cv2

# 读取照片
image = plt.imread("picture.jpg")

# 选中左边区域
n1 = image[:500, :500]
plt.imshow(n1)

#  图片为三维数组，最高维度是图像的height，次高维是图像的width，最低为是RGB颜色
# 灰度处理, 将紫色显示出来
# 0.3, 0, 0.7
n2 = np.array([0.4, 0, 0.6])  # 数组点乘 最里层与数组相乘 三通道变成单通道
# 将n1的颜色值与n2点乘
x = np.dot(n1, n2)

# 灰度处理另外一种方法
# n3 = n1.copy()
# n3[:, :, 0] = n3[:, :, 0] * 1  # blue
# n3[:, :, 1] = n3[:, :, 1] * 1  # green
# n3[:, :, 2] = n3[:, :, 2] * 1  # red
# im = np.sum(n3, axis=2)

# 二值化
ret, thresh = cv2.threshold(x, 200, 255, cv2.THRESH_BINARY)
plt.imshow(thresh, cmap="gray")

# findContours 需要uint8
thresh = np.array(thresh).astype(np.uint8)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print(len(contours))  # 输出轮廓个数

for cnt in contours:
    (x, y, w, h) = cv2.boundingRect(cnt)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

plt.imshow(image)
plt.show()
